package com.zhp.farmerclient.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Data
@Slf4j
public class JwtUtils {
    //7天过期
    private static long expire = 604800;
    //32位秘钥
    private static String serect = "abcdfghiabcdfghiabcdfghiabcdfghi";
    //生成token
    public static String generateToken(int id) {
        Date now = new Date();
        Date expiration = new Date(now.getTime()+1000*expire);
        return Jwts.builder().setHeaderParam("type","JWT")
                .setSubject(String.valueOf(id))
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512,serect)
                .compact();
    }

    //解析token
    public static Claims getClaimByToken(String token) {
       try {
           return Jwts.parser()
                   .setSigningKey(serect)
                   .parseClaimsJws(token)
                   .getBody();
       }catch (Exception e){
//           Log.debug("validate is token error",e);
           return null;
       }
    }

    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
